<script setup lang="ts">
import {
  ElRow,
  ElCol,
  ElInput,
  ElButton,
  ElCheckbox,
  ElMessage,
  ElMessageBox,
  ElAlert,
} from "element-plus";
import { ref, onMounted, onUnmounted, watch } from "vue";
import { DocumentEditor } from "@onlyoffice/document-editor-vue";
const scriptUrl = defineModel("scriptUrl");
const demoFileUrl = defineModel("demoFileUrl");
const demoConfigType = defineModel("demoConfigType");
const demoConfigMode = defineModel("demoConfigMode");
interface Props {
  scriptUrl?: string;
}

defineOptions({
  name: "ContentControllDemo",
});

const props = withDefaults(defineProps<Props>(), {});

const getUuid = function () {
  return "xxxxxxxxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

const VITE_ONLY_OFFICE_BASE_URL = import.meta.env.VITE_ONLY_OFFICE_BASE_URL;
const url = ref("http://47.94.91.67/demo_file/demo.docx");
const containerRef = ref();

const init = function () {
  config.value.document.key = getUuid();
  config.value.document.url = demoFileUrl.value;
  config.value.document.type = demoConfigType.value;
  config.value.editorConfig.mode = demoConfigMode.value;
  documentEditorKey.value = config.value.document.key;
};


let containerWidth = 0;
let containerHeight = 0;
let documentEditorKey = ref("");
onMounted(() => {
  containerWidth = containerRef.value.parentNode.offsetWidth;
  containerHeight = containerRef.value.parentNode.offsetHeight;
  if (containerHeight > 800) {
    containerHeight = 800;
  }
  containerRef.value.style.height = containerHeight + "px";
  documentEditorKey.value = getUuid();
  init();
});

onUnmounted(() => { });

watch(demoFileUrl, async (newsDemoFileUrl, oldDemoFileUrl) => { });

let currentConnector = null;
let contentItemRowDemo = {
  type: "text|image|checkbox",
  tag: "tag",
  InternalId: "1_3",
  value: "用于text类型",
  // 用户单选和多选
  group: [{ type: "checkbox", tag: "", InternalId: "1_3", checked: false }],
};
let contentItemList = ref([]);
const onDocumentReady = () => {
  console.log("onDocumentReady");
  currentConnector = DocEditor.instances.docEditor.createConnector();
  window.connector = currentConnector;
  insertParagraph(function () {
    insertParagraph(function () {
      insertTextControll("tage_1", function () {
        insertParagraph(function () {
          insertParagraph(function () {
            insertCheckboxGroupControll("tag|2", function () {
              insertCheckboxControll("tag|2", function () {
                

              });
            });
          });
        });
      });
    });
  });


  currentConnector.attachEvent("onChangeContentControl", function (e) {
    console.log(e);
    if (!e.Tag.startsWith("@")) {
      for (var i = 0; i < contentItemList.value.length; i++) {
        if (e.InternalId == contentItemList.value[i].InternalId) {
          let tempContentItem = contentItemList.value[i];
          currentConnector.executeMethod(
            "GetFormValue2",
            [e.InternalId],
            function (resultValue) {
              tempContentItem.value = resultValue;
            }
          );
        }
      }
    } else if (e.Tag.startsWith("@checkbox")) {
      let typeIdArr = e.Tag.split("_");
      let type = typeIdArr[0];
      let groupTag = typeIdArr[1];
      let itemInternalId = typeIdArr[2];
      console.log(type, groupTag, itemInternalId);
      for (var i = 0; i < contentItemList.value.length; i++) {
        if (groupTag != contentItemList.value[i].tag) {
          continue;
        }
        let groupList = contentItemList.value[i].group;
        console.log(groupList);
        for (var j = 0; j < groupList.length; j++) {
          let currentItem = groupList[j];
          if (e.Tag == currentItem.tag) {
            currentConnector.executeMethod(
              "GetFormValue2",
              [e.InternalId],
              function (resultValue) {
                console.log(1111, e.InternalId, resultValue, currentItem);
                currentItem.checked = resultValue;
              }
            );
          }
        }
      }
    }
  });
};

var config = ref({
  type: "desktop",
  // "type": "mobile",
  documentType: "word",
  historyList: {
    history: [],
    currentVersion: "1",
  },
  document: {
    title: "通用模板.docx",
    // url: "https://d2nlctn12v279m.cloudfront.net/assets/docs/samples/zh/demo.docx",
    url: "",
    permissions: {
      print: true,
      download: true,
      edit: true,
    },
    fileType: "docx",
    key: getUuid(),
  },
  editorConfig: {
    customization: {
      autosave: false,
      compactToolbar: false,
      forcesave: true,
      toolbarNoTabs: true,
      help: false,
      compactHeader: false,
      hideRightMenu: true,
      plugins: true,
      uiTheme: "theme-light",
    },
    mode: "edit",
    callbackUrl:
      "https://api.docs.onlyoffice.com/dummyCallback",
    lang: "zh-CN",
    user: {
      name: "曹瑞剑雄",
      id: "104",
    },
  },
});



let tagExist = function (tag) {
  for (var i = 0; i < contentItemList.value.length; i++) {
    if (tag == contentItemList.value[i].tag) {
      return true;
    }
  }
  return false;
};
let findByTag = function (tag) {
  for (var i = 0; i < contentItemList.value.length; i++) {
    if (tag == contentItemList.value[i].tag) {
      return contentItemList.value[i];
    }
  }
  return undefined;
};
let deleteContentItem = function (contentItem) {
  for (var i = 0; i < contentItemList.value.length; i++) {
    let temp = contentItemList.value[i];
    if ("text" == temp.type) {
      if (contentItem.InternalId == temp.InternalId) {
        contentItemList.value.splice(i, 1);
        break;
      }
    }
  }
};

let insertControll = function (type) {
  ElMessageBox.prompt("请输入tag", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(({ value }) => {
    if (value == undefined || "" == value) {
      ElMessage.error("请输入tag");
      return;
    }
    if (tagExist(value)) {
      ElMessage.error("tag已存在，请重新输入");
      return;
    }
    if ("text" == type) {
      insertTextControll(value);
    }
    if ("checkboxgroup" == type) {
      insertCheckboxGroupControll(value);
    }
  });
};

let insertParagraph = function (callback) {
  if (callback == undefined) {
    callback = function () { };
  }
  currentConnector.callCommand(function () {
    var oDocument = Api.GetDocument();
    var oParagraph = Api.CreateParagraph();
    var oRun = Api.CreateRun();
    oRun.AddText("    ");
    oParagraph.AddElement(oRun);
    oDocument.Push(oParagraph);
    oRun.MoveCursorToPos(0);
  }, callback);
};

let insertGapBlank = function (callback) {
  if (callback == undefined) {
    callback = function () { };
  }
  currentConnector.callCommand(function () {
    var oDocument = Api.GetDocument();
    var oParagraph = Api.CreateParagraph();
    var oRun = Api.CreateRun();
    oRun.AddText("    ");
    oParagraph.AddElement(oRun);
    oDocument.InsertContent([oParagraph], true);
    oRun.MoveCursorToPos(4);
  }, callback);
};

/********************  文本控件 **********************/
let insertTextControll = function (tag, callback) {
  console.log(tag);
  currentConnector.executeMethod(
    "AddContentControl",
    [2, { "Tag": tag }],
    function (resultValue) {
      console.log(resultValue);
      insertParagraph(function () {
        insertParagraph(function () {
          contentItemList.value.push({
            type: "text",
            tag: tag,
            InternalId: resultValue["InternalId"],
            value: "",
          });
          if (callback != undefined) {
            callback();
          }
        });
      });
    }
  );
};

let deleteTextControll = function (contentItem) {
  currentConnector.executeMethod(
    "RemoveContentControl",
    [contentItem.InternalId],
    function () {
      deleteContentItem(contentItem);
    }
  );
};

let changeText = function (contentItem) {
  currentConnector.executeMethod(
    "SetFormValue2",
    [contentItem.InternalId, contentItem.value],
    null
  );
};
/********************  文本控件 **********************/

/********************  多选控件 **********************/
let insertCheckboxGroupControll = function (tag, callback) {
  insertParagraph(function () {
    contentItemList.value.push({
      type: "checkboxgroup",
      tag: tag,
      group: [],
    });
    insertParagraph(function () {
      if (callback != undefined) {
        callback();
      }
    });
  });
};
let insertCheckboxControll = function (tag, callback) {
  let checkboxGroup = findByTag(tag);
  if (!checkboxGroup) {
    return;
  }
  let checkboxTag = "@checkbox_" + tag + "_" + getUuid();
  let InternalId = getUuid();
  currentConnector.executeMethod(
    "AddContentControlCheckBox",
    [
      { Checked: false, CheckedSymbol: 9745 },
      { Tag: checkboxTag, PlaceHolderText: checkboxTag },
    ],
    function () {
      currentConnector.executeMethod("MoveCursorToEnd", [false], function () {
        insertGapBlank(function () {
          checkboxGroup.group.push({
            type: "checkbox",
            tag: checkboxTag,
            InternalId: InternalId,
            checked: false,
          });
          if (callback != undefined) {
            callback();
          }
        });
      });
    }
  );
};
let checkboxChange = function (groupTag, currentItem) {
  let checkboxGroup = findByTag(groupTag);
  if (!checkboxGroup) {
    return;
  }
  let findInternalIdCallback = function (resultValue) {
    var tagMap = tagArrToMap(checkboxGroup.group);
    for (let i = 0; i < resultValue.length; i++) {
      if (tagMap[resultValue[i].Tag] != undefined) {
        tagMap[resultValue[i].Tag] = resultValue[i].InternalId;
      }
    }
    for (let i = 0; i < checkboxGroup.group.length; i++) {
      let checkboxItem = checkboxGroup.group[i];
      if (tagMap[checkboxItem.tag] == undefined) {
        continue;
      }
      currentConnector.executeMethod(
        "SetFormValue2",
        [tagMap[checkboxItem.tag], checkboxItem.checked],
        null
      );
    }
  };
  findInternalIdByTags(checkboxGroup.group, findInternalIdCallback);
};
/********************  多选控件 **********************/
let tagArrToMap = function (tagArr) {
  let tagMap = {};
  for (let i = 0; i < tagArr.length; i++) {
    tagMap[tagArr[i].tag] = "";
  }
  return tagMap;
};
let findInternalIdByTags = function (tagArr, callback) {
  currentConnector.executeMethod("GetAllContentControls", null, callback);
};


</script>

<template>
  <di class="onlyoffice_demo_container" ref="containerRef">
    <el-row style="height: 100%;overflow: scroll;">
      <el-col :span="9">
        <div style="
            width: 100%;
            height: 100%;
            overflow: scroll;
            background: #ffffff;
          ">
          <el-row class="gap_row">
            <el-col :span="24">
              <div class="grid-content ep-bg-purple-dark" />
              <el-alert style="height: 60px;font-size: 15px;font-weight: 600;margin-bottom: 15px;" title="你可以左右两边都输入文字或者打钩试试" type="error" />
              <el-button type="primary" @click="insertControll('text')">插入文本控件</el-button>
              <el-button type="primary" @click="insertControll('checkboxgroup')">插入多选控件</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <template v-for="contentItem in contentItemList">
                <el-row class="gap_row" v-if="contentItem.type == 'text'">
                  <el-col :span="18">
                    <el-input v-model="contentItem.value" placeholder="请输入文字" style="width: 340px"
                      @input="changeText(contentItem)" />
                  </el-col>
                  <el-col :span="6">
                    <el-button type="danger" @click="deleteTextControll(contentItem)">删除</el-button>
                  </el-col>
                </el-row>
                <el-row class="gap_row" v-if="contentItem.type == 'checkboxgroup'">
                  <el-col class="gap_row bg-purple" :span="24" style="margin-top: 15px">
                    <el-checkbox v-for="checkboxItem in contentItem.group" v-model="checkboxItem.checked"
                      :label="checkboxItem.tag" size="large" border
                      @change="checkboxChange(contentItem.tag, checkboxItem)" />
                  </el-col>
                  <el-col :span="24">
                    <el-button style="width: 100%" type="success" plain
                      @click="insertCheckboxControll(contentItem.tag)">插入多选</el-button>
                  </el-col>
                </el-row>
              </template>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="15">
        <DocumentEditor id="docEditor"
          :documentServerUrl="VITE_ONLY_OFFICE_BASE_URL" :config="config" :events_onDocumentReady="onDocumentReady"
          height="100%" />
      </el-col>
    </el-row>
  </di>
</template>

<style scoped>
.onlyoffice_demo_container {
  width: 100%;
  height: 100%;
  display: inline-block;
}

.gap_row {
  margin-top: 15px;
  margin-bottom: 15px;
}

.bg-purple {
  min-height: 36px;
  line-height: 36px;
  background: #d3dce6;
}
</style>
